package httputil

import (
	"awesomeProject1/pkg/json"
	"github.com/simplechain-org/client/log"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
)

func PostJson(uri string, jsons interface{}) ([]byte, error) {
	jsonParam, errs := json.Marshal(jsons) //转换成JSON返回的是byte[]
	if errs != nil {
		log.Error(errs.Error())
		return nil, errs
	}

	//发送请求
	req, err := http.NewRequest("POST", uri, strings.NewReader(string(jsonParam)))
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json;charset=utf-8")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	defer resp.Body.Close()
	//响应
	response, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Error("Read failed:", "err", err.Error())
		return nil, err
	}

	//返回结果
	return response, nil
}

func PostForm(uri string, paras map[string][]string) ([]byte, error) {

	resp, err := http.PostForm(uri, url.Values(paras))
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	return body, nil

}

func Get(uri string) ([]byte, error) {

	resp, err := http.Get(uri)
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}

	return body, nil

}
